﻿using MxWeiXinPF.API.Payment.Tenpay;
using MxWeiXinPF.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;//第一步：导入此命名空间

namespace MxWeiXinPF.Web.weixin.jiaoshuifei
{
    /// <summary>
    /// jsf_bindOne 的摘要说明
    /// </summary>
    public class jsf_bindOne : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";

            Dictionary<string, object> dic = new Dictionary<string, object>();

            ///接口用到的key
            string key = "";
            ///接口用到的用户名
            string wxusername = "";
            //接口地址
            string apiurl = "";
            string username = MyCommFun.QueryString("username");
            string consno = MyCommFun.QueryString("usernumber");

            string openid = HttpContext.Current.Session["openid"].ToString();
            if (string.IsNullOrEmpty(openid))
            {
                //提示错误
                dic.Add("msg", "openid失效，请重新获取");
                dic.Add("succuss", 100);
                context.Response.Write(JsonConvert.SerializeObject(dic));
                return;

            }
            int wid = MyCommFun.RequestWid();
            MxWeiXinPF.BLL.shuifei_baseinfo _baseInfoBLL = new BLL.shuifei_baseinfo();
            Model.shuifei_baseinfo baseinfoModel=_baseInfoBLL.GetModelByWid(wid);
            if (baseinfoModel!=null)
            {
                wxusername = baseinfoModel.api_UserName;
                key = baseinfoModel.api_Key;
                apiurl = baseinfoModel.api_url;
            }


            string actionType = MyCommFun.QueryString("actionType");
            string msg = string.Empty;
          
            //绑定
            if (actionType=="bind")
            {
                if (!Bind(username, consno, openid, wxusername,key,apiurl, "", out msg))
                {
                    dic.Add("msg",msg);
                    dic.Add("succuss", 0);
                    context.Response.Write(JsonConvert.SerializeObject(dic));
                    return;
                }
                dic.Add("msg", msg);
                dic.Add("succuss", 1);
                context.Response.Write(JsonConvert.SerializeObject(dic));
                return;
            }
                //解绑
            else if (actionType=="unbind")
            {
                 if (!Unbind(consno,wxusername,key,apiurl,openid,"",out msg))
                {
                    dic.Add("msg", msg);
                    dic.Add("succuss", 0);
                    context.Response.Write(JsonConvert.SerializeObject(dic));
                    return;
                }
                 dic.Add("msg", msg);
                 dic.Add("succuss", 1);
                 context.Response.Write(JsonConvert.SerializeObject(dic));
                return;
            }
            else if (actionType=="GetUserNameByconsno")
            {
                  if (!GetUserNameByconsno(consno,wxusername,key,apiurl,"",false,username,out msg))
                {
                    dic.Add("msg", msg);
                    dic.Add("succuss", 0);
                    context.Response.Write(JsonConvert.SerializeObject(dic));
                    return;
                }
                 dic.Add("msg", msg);
                 dic.Add("succuss", 1);
                 context.Response.Write(JsonConvert.SerializeObject(dic));
                return;
            }
            else if (actionType=="fixApply")
            {
                string fixType = MyCommFun.QueryString("fixType");
                string name = MyCommFun.QueryString("username");
                string phone = MyCommFun.QueryString("phone");
                string address = MyCommFun.QueryString("address");
                string remark = MyCommFun.QueryString("remark");
                string imgFile = MyCommFun.QueryString("imgFile");

                if (string.IsNullOrEmpty(fixType) || string.IsNullOrEmpty(name) || string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(address))
                {
                     dic.Add("msg", "请完善资料");
                    dic.Add("succuss", 0);
                    context.Response.Write(JsonConvert.SerializeObject(dic));
                    return;
                }
                BLL.shuifei_baoxiu baoxiubll = new BLL.shuifei_baoxiu();
                Model.shuifei_baoxiu baoxiumodel = new Model.shuifei_baoxiu();
                baoxiumodel.wid = Convert.ToInt32(wid);
                baoxiumodel.openid = openid;
                baoxiumodel.bx_type = fixType;
                baoxiumodel.contact_person = name;
                baoxiumodel.contact_tel = phone;
                baoxiumodel.addr = address;
                baoxiumodel.bx_content = remark;
                baoxiumodel.bx_pic = imgFile;
                baoxiumodel.create_time = DateTime.Now;

                if (baoxiubll.Add(baoxiumodel)<=0)
                {
                      dic.Add("msg", "提交失败");
                    dic.Add("succuss", 0);
                    context.Response.Write(JsonConvert.SerializeObject(dic));
                    return;
                }
                dic.Add("msg", "提交成功");
                dic.Add("succuss", 1);
                context.Response.Write(JsonConvert.SerializeObject(dic));
                return;
            }
                //保存订单
            else if (actionType=="SaveOrder")
            {
                DateTime now = DateTime.Now;
                string amount = MyCommFun.QueryString("amount");//单位元
                Model.orders model = new Model.orders();
                model.order_no = "J" + Utils.GetOrderNumber(); //订单号J开头为交水费
                model.order_amount = Convert.ToDecimal(amount);//单位元

                model.wid = wid;
                model.openid = openid;
                model.modelName = Model.orderModelNameEnum.缴水费.ToString();//  "交水费";
                model.modelCode = Model.orderModelCodeEnum.jiaoshuifei.ToString();
                model.notify_id = wid.ToString();
                model.modelActionId = 0;
                model.add_time = now;
                model.status = 1;
                model.orderSubject = username+ "("+ consno +")水费";

                int result = new BLL.orders().Add(model);
                if (result < 1)
                {
                    dic.Add("msg", "请重新提交订单");
                    dic.Add("succuss", 0);
                    context.Response.Write(JsonConvert.SerializeObject(dic));
                    return;
                }
                MxWeiXinPF.Model.shuifei_payment_record paymodel = new Model.shuifei_payment_record();
                paymodel.create_time = now;
                paymodel.openid = openid;
                paymodel.wid = wid;
                paymodel.username = username;
                paymodel.payment_money = Convert.ToDecimal(amount);///单位元
                paymodel.consno = consno;
                paymodel.orderID = model.order_no;
                paymodel.pay_status = 0;

                BLL.shuifei_payment_record _shuifei_payment_recordBLL = new BLL.shuifei_payment_record();
                if (_shuifei_payment_recordBLL.Add(paymodel) < 1)
                {
                    dic.Add("msg", "请重新提交订单");
                    dic.Add("succuss", 0);
                    context.Response.Write(JsonConvert.SerializeObject(dic));
                    return;
                }
                dic.Add("succuss", 1);
                dic.Add("order_no", result);
                context.Response.Write(JsonConvert.SerializeObject(dic));
            }
        }
        /// <summary>
        /// 绑定户号
        /// </summary>
        /// <param name="username"></param>
        /// <param name="consno"></param>
        /// <param name="openid"></param>
        /// <param name="wxusername"></param>
        /// <param name="extend"></param>
        /// <returns></returns>
        public bool Bind(string username, string consno, string openid, string wxusername, string key,string apiurl,string extend,out string msg)
        {
            msg = string.Empty;
            //验证户名是否正确
            if (!GetUserNameByconsno(consno, wxusername, key,apiurl, extend, true, username, out msg))
            {
                return false;
            }
            string tradeNo = "1001";
            string datetimeStr = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            StringBuilder strBuf = new StringBuilder();
            strBuf.Append(wxusername);
            strBuf.Append(tradeNo);
            strBuf.Append(openid);

            strBuf.Append(consno);
            strBuf.Append(extend);
            strBuf.Append(datetimeStr);

            strBuf.Append(key);
            string sign = MD5Util.GetMD5(strBuf.ToString(), Encoding.UTF8.ToString()).ToUpper();
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("consno", consno);
            sParaTemp.Add("extend", extend);
            sParaTemp.Add("openid", openid);
            sParaTemp.Add("randomstr", datetimeStr);
            sParaTemp.Add("tradecode", tradeNo);
            sParaTemp.Add("username", wxusername);
            sParaTemp.Add("sign", sign);

            string para = JsonConvert.SerializeObject(sParaTemp);

            jsfservice.WXWaterServiceSoapClient jsfservice = new jsfservice.WXWaterServiceSoapClient("WXWaterServiceSoap12", apiurl);

            string returnMsg = jsfservice.wxProgress(para);

            if (string.IsNullOrEmpty(returnMsg))
            {
                msg = "returnMsg为null";
                return false;
            }
            Model.JSFResultModel resultModel = JsonConvert.DeserializeObject<Model.JSFResultModel>(returnMsg);
            if (resultModel == null)
            {
                msg = "resultModel为null";
                return false;
            }
            //if (resultModel.sign != sign)
            //{
            //    msg = resultModel.rtnmsg;
            //    return false;
            //}
            if (resultModel.rtncode != "OK")
            {
                msg = resultModel.rtnmsg;
                return false;
            }
            msg = resultModel.rtnmsg;
            return true;

        }
        /// <summary>
        /// 根据用户号获取用户信息
        /// </summary>
        /// <param name="consno"></param>
        /// <param name="wxusername"></param>
        /// <param name="extend"></param>
        /// <param name="consname"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool GetUserNameByconsno(string consno, string wxusername, string key,string apiurl, string extend,bool checkName, string consname, out string msg)
        {
            msg = string.Empty;
            string tradeNo = "1003";
            string datetimeStr = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            StringBuilder strBuf = new StringBuilder();
            strBuf.Append(wxusername);
            strBuf.Append(tradeNo);
 
            strBuf.Append(consno);
            strBuf.Append(extend);
            strBuf.Append(datetimeStr);

            strBuf.Append(key);
            string sign = MD5Util.GetMD5(strBuf.ToString(), Encoding.UTF8.ToString()).ToUpper();
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("consno", consno);
            sParaTemp.Add("extend", extend); 
            sParaTemp.Add("randomstr", datetimeStr);
            sParaTemp.Add("tradecode", tradeNo);
            sParaTemp.Add("username", wxusername);
            sParaTemp.Add("sign", sign);

            string para = JsonConvert.SerializeObject(sParaTemp);
            jsfservice.WXWaterServiceSoapClient jsfservice = new jsfservice.WXWaterServiceSoapClient("WXWaterServiceSoap12", apiurl);

            string returnMsg = jsfservice.wxProgress(para);
            if (string.IsNullOrEmpty(returnMsg))
            {
                msg = "returnMsg=null";
                return false;   
            }
            Model.JSFResultModel resultModel = JsonConvert.DeserializeObject<Model.JSFResultModel>(returnMsg);
            if (resultModel==null)
            {
                msg = "resultModel=null";
                return false;   
            }
            if (resultModel.rtncode!="OK")
            {
                msg = resultModel.rtnmsg;
                return false;  
            }
            if (checkName)
            {
                if (resultModel.consname != consname)
                {
                    msg = "用户名不正确";
                    return false;
                }
            }
            msg = resultModel.consname;
            return true;
        }

      /// <summary>
      /// 解绑户号
      /// </summary>
      /// <param name="consno"></param>
      /// <param name="wxusername"></param>
      /// <param name="openid"></param>
      /// <param name="extend"></param>
      /// <param name="msg"></param>
      /// <returns></returns>
        public bool Unbind(string consno, string wxusername, string key, string apiurl, string openid, string extend, out string msg)
        {
            msg = string.Empty;
            string tradeNo = "1002";
            string datetimeStr = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            StringBuilder strBuf = new StringBuilder();
            strBuf.Append(wxusername);
            strBuf.Append(tradeNo);
            strBuf.Append(openid);
            strBuf.Append(consno);
            strBuf.Append(extend);
            strBuf.Append(datetimeStr);
            strBuf.Append(key);
            string sign = MD5Util.GetMD5(strBuf.ToString(), Encoding.UTF8.ToString()).ToUpper();
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("consno", consno);
            sParaTemp.Add("extend", extend);
            sParaTemp.Add("openid", openid);
            sParaTemp.Add("randomstr", datetimeStr);
            sParaTemp.Add("tradecode", tradeNo);
            sParaTemp.Add("username", wxusername);
            sParaTemp.Add("sign", sign);

            string para = JsonConvert.SerializeObject(sParaTemp);
            jsfservice.WXWaterServiceSoapClient jsfservice = new jsfservice.WXWaterServiceSoapClient("WXWaterServiceSoap12", apiurl);

            string returnMsg = jsfservice.wxProgress(para);
            if (string.IsNullOrEmpty(returnMsg))
            {
                msg = "returnMsg=null";
                return false;
            }
            Model.JSFResultModel resultModel = JsonConvert.DeserializeObject<Model.JSFResultModel>(returnMsg);
            if (resultModel == null)
            {
                msg = "resultModel=null";
                return false;
            }
            //if (resultModel.sign != sign)
            //{
            //    msg = "非法请求";
            //    return false;
            //}
            if (resultModel.rtncode != "OK")
            {
                msg = resultModel.rtnmsg;
                return true;
            }
            msg = resultModel.rtnmsg;
            return true;
        }

       /// <summary>
       /// 根据户号获取用户欠费信息
       /// </summary>
       /// <param name="consno"></param>
       /// <param name="wxusername"></param>
       /// <param name="extend"></param>
       /// <param name="msg"></param>
       /// <returns></returns>
        public Model.JSFResultModel GetOwnInfo(string consno, string wxusername, string key,string apiurl, string extend, out string msg)
        {
            msg = string.Empty;
            string tradeNo = "1004";
            string datetimeStr = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            StringBuilder strBuf = new StringBuilder();
            strBuf.Append(wxusername);
            strBuf.Append(tradeNo);

            strBuf.Append(consno);
            strBuf.Append(extend);
            strBuf.Append(datetimeStr);

            strBuf.Append(key);
            string sign = MD5Util.GetMD5(strBuf.ToString(), Encoding.UTF8.ToString()).ToUpper();
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("consno", consno);
            sParaTemp.Add("extend", extend);
            sParaTemp.Add("randomstr", datetimeStr);
            sParaTemp.Add("tradecode", tradeNo);
            sParaTemp.Add("username", wxusername);
            sParaTemp.Add("sign", sign);

            string para = JsonConvert.SerializeObject(sParaTemp);
            jsfservice.WXWaterServiceSoapClient jsfservice = new jsfservice.WXWaterServiceSoapClient("WXWaterServiceSoap12", apiurl);
            string returnMsg = jsfservice.wxProgress(para);
            if (string.IsNullOrEmpty(returnMsg))
            {
                msg = "returnMsg=null";
                return null;
            }
            Model.JSFResultModel resultModel = JsonConvert.DeserializeObject<Model.JSFResultModel>(returnMsg);
            if (resultModel == null)
            {
                msg = "resultModel=null";
                return null;
            }
            if (resultModel.rtncode != "OK")
            {
                msg = resultModel.rtnmsg;
                return null;
            }

            return resultModel;
        }



        /// <summary>
        /// 用户缴费
        /// </summary>
        /// <param name="username">wx</param>
        /// <param name="consno"></param>
        /// <param name="openid"></param>
        /// <param name="wxusername"></param>
        /// <param name="extend"></param>
        /// <returns></returns>
        public bool PayDo(string orderID,int amount, string consno, string openid, string wxusername, string key, string apiurl,string extend, out string msg,out string api_rtncode)
        {
            msg = string.Empty;
            api_rtncode = "";
            string tradeNo = "1005";
            string datetimeStr = DateTime.Now.ToString("yyyyMMddhhmmssfff");
            StringBuilder strBuf = new StringBuilder();
            strBuf.Append(wxusername);
            strBuf.Append(tradeNo);
            strBuf.Append(consno);
            strBuf.Append(openid);
            strBuf.Append(orderID);
            strBuf.Append(DateTime.Now.ToString("yyyyMMdd"));
            strBuf.Append(amount);

            strBuf.Append(extend);
            strBuf.Append(datetimeStr);

            strBuf.Append(key);
            string sign = MD5Util.GetMD5(strBuf.ToString(), Encoding.UTF8.ToString()).ToUpper();
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("consNo", consno);
            sParaTemp.Add("extend", extend);
            sParaTemp.Add("openid", openid);
            sParaTemp.Add("randomstr", datetimeStr);
            sParaTemp.Add("tradecode", tradeNo);
            sParaTemp.Add("username", wxusername);
            sParaTemp.Add("wxSerial", orderID);
            sParaTemp.Add("wxDate", DateTime.Now.ToString("yyyyMMdd"));
            sParaTemp.Add("rcvAmt", amount.ToString());
            sParaTemp.Add("sign", sign);

            string para = JsonConvert.SerializeObject(sParaTemp);

            jsfservice.WXWaterServiceSoapClient jsfservice = new jsfservice.WXWaterServiceSoapClient("WXWaterServiceSoap12", apiurl);

            string returnMsg = jsfservice.wxProgress(para);

            if (string.IsNullOrEmpty(returnMsg))
            {
                msg = "returnMsg为null";
                
                return false;
            }
            Model.JSFResultModel resultModel = JsonConvert.DeserializeObject<Model.JSFResultModel>(returnMsg);
            if (resultModel == null)
            {
                msg = "resultModel为null";
                return false;
            }
            //if (resultModel.sign != sign)
            //{
            //    msg = resultModel.rtnmsg;
            //    api_rtncode = resultModel.rtncode;
            //    return false;
            //}
            if (resultModel.rtncode != "OK")
            {
                msg = resultModel.rtnmsg;
                api_rtncode = resultModel.rtncode;
                return false;
            }
            msg = resultModel.rtnmsg;
            api_rtncode = resultModel.rtncode;
            return true;

        }
      
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}